<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const errorMessage = ref('')
const uploadLoading = ref(false)
const imagePreview = ref('')

const formData = ref({
    username: '',
    password: '',
    confirmPassword: '',
    nickname: '',
    avatar: '',
    status: 1
})

const validateForm = () => {
    if (!formData.value.username) {
        errorMessage.value = '请输入用户名'
        return false
    }
    if (!formData.value.password) {
        errorMessage.value = '请输入密码'
        return false
    }
    if (formData.value.password !== formData.value.confirmPassword) {
        errorMessage.value = '两次输入的密码不一致'
        return false
    }
    return true
}

const handleSubmit = async () => {
    try {
        if (!validateForm()) return

        loading.value = true
        errorMessage.value = ''

        const token = localStorage.getItem('token')
        const response = await fetch('http://localhost:3001/api/admin/create', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
                username: formData.value.username,
                password: formData.value.password,
                nickname: formData.value.nickname || undefined,
                avatar: formData.value.avatar || undefined,
                status: formData.value.status
            })
        })

        if (!response.ok) {
            const error = await response.json()
            throw new Error(error.message || '创建失败')
        }

        const data = await response.json()
        console.log('创建管理员响应:', data)
        
        if (data.code === 200) {
            alert('管理员创建成功')
            router.push('/system')
        } else {
            throw new Error(data.message || '创建失败')
        }
    } catch (error) {
        console.error('创建管理员失败:', error)
        if (error.name === 'SyntaxError') {
            errorMessage.value = '服务器响应格式错误'
        } else {
            errorMessage.value = error.message || '创建失败��请重试'
        }
    } finally {
        loading.value = false
    }
}

const handleImageUpload = async (e) => {
    const file = e.target.files[0]
    if (!file) return
    
    if (!file.type.startsWith('image/')) {
        errorMessage.value = '请上传图片文件'
        return
    }
    
    if (file.size > 2 * 1024 * 1024) {
        errorMessage.value = '图片大小不能超过2MB'
        return
    }

    try {
        uploadLoading.value = true
        errorMessage.value = ''

        const uploadFormData = new FormData()
        uploadFormData.append('files', file)

        const token = localStorage.getItem('token')
        const response = await fetch('http://localhost:3001/api/upload-images', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`
            },
            body: uploadFormData
        })

        const data = await response.json()
        console.log('上传响应:', data)

        if (response.ok && data.success) {
            if (data.imageUrls && data.imageUrls.length > 0) {
                formData.value.avatar = data.imageUrls[0]
                imagePreview.value = `http://localhost:3001${data.imageUrls[0]}`
                console.log('设置的头像URL:', formData.value.avatar)
            } else {
                throw new Error('未获取到上传的图片URL')
            }
        } else {
            throw new Error(data.message || '上传失败')
        }
    } catch (error) {
        console.error('上传图片失败:', error)
        errorMessage.value = error.message || '上传失败，请重试'
    } finally {
        uploadLoading.value = false
    }
}
</script>

<template>
    <div class="add-admin-page">
        <div class="page-header">
            <h2>添加管理员</h2>
        </div>

        <div class="form-container">
            <form @submit.prevent="handleSubmit" class="admin-form">
                <div v-if="errorMessage" class="error-message">
                    {{ errorMessage }}
                </div>

                <div class="form-group">
                    <label>用户名</label>
                    <input 
                        v-model="formData.username"
                        type="text"
                        placeholder="请输入用户名"
                        required
                    >
                </div>

                <div class="form-group">
                    <label>密码</label>
                    <input 
                        v-model="formData.password"
                        type="password"
                        placeholder="请输入密码"
                        required
                    >
                </div>

                <div class="form-group">
                    <label>确认密码</label>
                    <input 
                        v-model="formData.confirmPassword"
                        type="password"
                        placeholder="请再次输入密码"
                        required
                    >
                </div>

                <div class="form-group">
                    <label>昵称</label>
                    <input 
                        v-model="formData.nickname"
                        type="text"
                        placeholder="请输入昵称"
                    >
                </div>

                <div class="form-group">
                    <label>头像</label>
                    <div class="upload-container">
                        <div class="preview-area" v-if="imagePreview">
                            <img :src="imagePreview" alt="头像预览" class="image-preview">
                            <button 
                                type="button" 
                                class="remove-image"
                                @click="() => {
                                    imagePreview = ''
                                    formData.avatar = ''
                                }"
                            >
                                <i class="fa-solid fa-times"></i>
                            </button>
                        </div>
                        <div v-else class="upload-area">
                            <input
                                type="file"
                                accept="image/*"
                                @change="handleImageUpload"
                                :disabled="uploadLoading"
                                class="file-input"
                            >
                            <div class="upload-placeholder">
                                <i class="fa-solid fa-cloud-upload-alt"></i>
                                <span>{{ uploadLoading ? '上传中...' : '点击或拖拽上传图片' }}</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label>状态</label>
                    <select v-model="formData.status">
                        <option :value="1">启用</option>
                        <option :value="0">禁用</option>
                    </select>
                </div>

                <div class="form-actions">
                    <button 
                        type="button" 
                        class="cancel-btn"
                        @click="router.back()"
                    >
                        取消
                    </button>
                    <button 
                        type="submit"
                        class="submit-btn"
                        :disabled="loading"
                    >
                        {{ loading ? '提交中...' : '提交' }}
                    </button>
                </div>
            </form>
        </div>
    </div>
</template>

<style scoped>
.add-admin-page {
    padding: 24px;
}

.page-header {
    margin-bottom: 24px;
}

.form-container {
    background: white;
    border-radius: 8px;
    padding: 24px;
    max-width: 600px;
    margin: 0 auto;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.admin-form {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

label {
    font-weight: 500;
    color: #374151;
}

input, select {
    padding: 8px 12px;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-size: 14px;
}

input:focus, select:focus {
    border-color: #1890ff;
    outline: none;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 24px;
}

.cancel-btn, .submit-btn {
    padding: 8px 16px;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s;
}

.cancel-btn {
    background: white;
    border: 1px solid #d1d5db;
}

.submit-btn {
    background: #1890ff;
    color: white;
    border: none;
}

.submit-btn:disabled {
    background: #d1d5db;
    cursor: not-allowed;
}

.error-message {
    padding: 12px;
    background: #fff2f0;
    border: 1px solid #ffccc7;
    border-radius: 6px;
    color: #ff4d4f;
}

.upload-container {
    width: 100%;
    margin-top: 8px;
}

.upload-area {
    position: relative;
    width: 100%;
    height: 120px;
    border: 2px dashed var(--border-color);
    border-radius: var(--border-radius);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
}

.upload-area:hover {
    border-color: var(--primary-color);
}

.file-input {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    color: var(--text-color-secondary);
}

.upload-placeholder i {
    font-size: 24px;
}

.preview-area {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: var(--border-radius);
    overflow: hidden;
}

.image-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.remove-image {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
}

.remove-image:hover {
    background: rgba(0, 0, 0, 0.7);
}
</style> 